const fs = require('fs');
const path = require('path');
const koa = require('koa');
const koaBody = require('koa-body');
const session = require('koa-session-minimal'); //微信小程序没有cookie
const prepare = require('./prepare');
const sessonAuth = require('./middleware/sessonAuth');

const app = new koa();

prepare();

// 使用session中间件
app.use(
  session({
    key: 'SESSION_ID',
    store: global.sessionStore,
    cookie: {
      maxAge: process.env.DEV !== 'true' ? 86400 * 2 * 1000 : 86400 * 365 * 1000, //  本地开发环境，2d过期，否则1年 unit:ms
      path: '/', // 写cookie所在的路径
      httpOnly: true,
      overwrite: false, // 是否允许重写
    },
  }),
);

app.use(
  koaBody({
    multipart: true,
    formidable: {
      hash: 'md5',
      maxFileSize: 30 * 1024 * 1024 * 1024,
    },
    onError(error, ctx) {
      global._logger.error(`::: body parse error :::`, error, ctx.path, ctx.request);
    },
  }),
);

// 加载中间件
app.use(sessonAuth);

/**
 * 路由自动加载目录规范：router autoloader
 * /routes 目录规范：仅存储route文件
 */
const routerMap = {};
const prefix = path.join(__dirname, 'routes');
const routerList = fs.readdirSync(prefix);
routerList.forEach(function(route) {
  console.log('route::', route);
  routerMap[route] = require(path.join(prefix, route));
  if (routerMap[route] && routerMap[route].routes) {
    app.use(routerMap[route].routes());
  }
});

app.host = process.env.IP || 'localhost';
app.port = process.env.PORT || 8080;

// eslint-disable-next-line no-unused-vars
app.on('error', function(err, ctx) {
  global._logger.info('server error', err.message, err.stack);
});

/**
 * 服务器启动任务
 */
const server = app.listen(app.port, app.host, function() {
  global._logger.info(
    `Koa server listening on ${server.address().address}:${server.address().port}`,
  );
});
